package launcher.simple.android.woblog.cn.widget;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class AlertDialogFragment extends DialogFragment implements
        DialogInterface.OnClickListener {
    public static final String EXTRA_TITLE = "title";
    public static final String EXTRA_MESSAGE = "message";
    public static final String EXTRA_POSITIVE = "positive";
    public static final String EXTRA_NEGATIVE = "negative";
    public static final String EXTRA_NEUTRAL = "neutral";
    public static final String EXTRA_OUTSIDE_CANCEL = "outside";
    private DialogInterface.OnClickListener mListener;

    public AlertDialogFragment() {
        setCancelable(false);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        if (bundle == null) {
            return super.onCreateDialog(savedInstanceState);
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        int positive = bundle.getInt(EXTRA_POSITIVE, 0);
        if (positive != 0) {
            builder.setPositiveButton(positive, this);
        }
        int negative = bundle.getInt(EXTRA_NEGATIVE, 0);
        if (negative != 0) {
            builder.setNegativeButton(negative, this);
        }
        int neutral = bundle.getInt(EXTRA_NEUTRAL, 0);
        if (neutral != 0) {
            builder.setNeutralButton(neutral, this);
        }

        AlertDialog dialog = builder.create();
        String title = bundle.getString(EXTRA_TITLE);
        if (title != null) {
            dialog.setTitle(title);
        }
        String message = bundle.getString(EXTRA_MESSAGE);
        if (message != null) {
            dialog.setMessage(message);
        }
        boolean cancelable = bundle.getBoolean(EXTRA_OUTSIDE_CANCEL, false);
        dialog.setCanceledOnTouchOutside(cancelable);
        return dialog;
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (mListener != null) {
            mListener.onClick(dialog, which);
        }
    }

    public void setOnClickListener(DialogInterface.OnClickListener l) {
        mListener = l;
    }
}
